package com.karaku.karaku_collector.util;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.WindowManager;

import com.karaku.karaku_collector.App;
import com.karaku.karaku_collector.common.KarakuActivityManager;

/**
 * Created by guopi on 2017/10/27 0027.
 */

public class ScreenManager {

    public interface Listener {
        void onScreenChanged(boolean isScreenOn);
    }

    private static ScreenManager instance;
    public static ScreenManager getInstance() {
        if (instance == null) {
            instance = new ScreenManager();
        }
        return instance;
    }

    private boolean screenOn = false;
    private Listener listener;

    private final BroadcastReceiver screenOnReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            updateScreenState(intent);
        }
    };

    private ScreenManager() {
        final IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        Intent intent = App.getInstance().registerReceiver(screenOnReceiver, filter);
        updateScreenState(intent);
    }

    public Listener getListener() {
        return listener;
    }

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    public boolean isScreenOn() {
        return screenOn;
    }

    public void screenOn() {
        LogUtil.d("SCREEN", "screenOn");
//        KarakuActivityManager.lastOrDefault().getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
//                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
//                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
//                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

//        PowerManager pm = (PowerManager) App.getInstance().getSystemService(Context.POWER_SERVICE);
//        PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "TAG");
//        wakeLock.acquire();
//        wakeLock.release();
    }

    private void updateScreenState(Intent intent) {
        if (intent == null) {
            return;
        }
        final String action = intent.getAction();
        if (Intent.ACTION_SCREEN_ON.equals(action)) {
            setScreenOn(true);
        } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
            setScreenOn(false);
        }
    }

    private void setScreenOn(boolean screenOn) {
        LogUtil.d("SCREEN", "setScreenOn:" + screenOn);
        if (this.screenOn == screenOn) {
            return;
        }
        this.screenOn = screenOn;
        if (listener != null) {
            listener.onScreenChanged(this.screenOn);
        }
    }

}
